#include <iostream>
#include <cassert>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>
#include <string>

using namespace std;

// 线程一旦被创建,几乎所有的资源都是共享的
// 一个线程中的同一变量改变,另一个也会同步改变,不会像进程一样,父进程和子进程同一变量不同值

int g_val = 0;

string fun()
{
    return "我是一个独立的方法";
}

// 新进程
void *thread_routine(void *args)
{
    const char *name = (const char *)args;
    while(true)
    {
        cout << "我是新线程,我正在运行! name: " << name << ":" << fun() << " g_val: " << g_val++ << " &val: " << &g_val << endl;
        sleep(1);
    }
}

int main()
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, thread_routine, (void *)"thread one");
    assert(0 == n);
    (void)n;

    // 主进程
    while(true)
    {
        char tidbuffer[64];
        snprintf(tidbuffer, sizeof(tidbuffer), "0x%x", tid);
        cout << "我是主线程,我正在运行!,我创建出来的线程的tid " << tidbuffer << ":" << fun() << " g_val: " << g_val << " &g_val: " << &g_val << endl;
        sleep(1);
    }

    return 0;
}